package leetcode.editor.cn;

import arithmetic2.ListNode;

//[24]两两交换链表中的节点
public class SwapNodesInPairs24{
public static void main(String[] args) {
   Solution solution = new SwapNodesInPairs24().new Solution();
   
}

  //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        //a or b is null ,return a;
        if (head == null || head.next == null) return head;
        ListNode originB = head.next;//!!! cache node.
        ListNode a = head;
        ListNode pri = null;
        //1 循环线下 2布
        while (a!=null && a.next!=null){
            // a  b  c  d
            // b  a  d  c
            ListNode b = a.next;
            ListNode c = b.next;
            a.next = c;//a->b >>> a->c
            b.next = a;//b->c >>> b->a
            if (pri != null) {//pri -> a >>> pri -> b
                pri.next = b;
            }
            pri = a;//pri = null 》》》 pri = a
            a = c;// cur = c ,current node
        }
        return originB;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}